var m = 0;

var model = 'FireFighter';
var color = 'Brown';
window.addEventListener('message', (e) => {
    if(e.data.room != null){
        sessionStorage.setItem("room", e.data.room);
    }
    if (e.data.model != null) {
        sessionStorage.setItem("model", e.data.model);
    }
    if (e.data.color != null) {
        sessionStorage.setItem("color", e.data.color);
    }
    if (e.data.username != null) {
        sessionStorage.setItem("username", e.data.username);
    }
    
}, false);



class Game1 {
    constructor() {
        if (!Detector.webgl) Detector.addGetWebGLMessage();

        this.container;
        this.player = {};
        this.animations = {};
        this.stats;
        this.controls;
        this.camera;
        this.scene;
        this.renderer;

        this.container = document.createElement('div');
        this.container.style.height = '100%';
        document.body.appendChild(this.container);

        const game = this;
        this.anims = ['Pointing Gesture','Pointing','Running','Talking','Turn','Walking'];

        this.assetsPath = 'assets/';

        this.clock = new THREE.Clock();

        this.init();

        window.onError = function (error) {
            console.error(JSON.stringify(error));
        }
    }

    init() {

        this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);
        this.camera.position.set(0, 200, 500);

        this.scene = new THREE.Scene();
        // this.scene.background = new THREE.Color(0x000000);
        // this.scene.background = new THREE.Color(0x29294b,0);
        // this.scene.fog = new THREE.Fog(0xa0a0a0, 700, 1800);

        // 创建一个纹理图片加载器加载图片
        var textureLoader = new THREE.TextureLoader();
        // 加载背景图片
        var texture = textureLoader.load(`assets/images/back.png`);
        // 纹理对象Texture赋值给场景对象的背景属性.background
        this.scene.background = texture;

        let light = new THREE.HemisphereLight(0xffffff, 0x444444);
        light.position.set(0, 200, 0);
        this.scene.add(light);

        light = new THREE.DirectionalLight(0xffffff);
        light.position.set(0, 200, 100);
        light.castShadow = true;
        light.shadow.camera.top = 180;
        light.shadow.camera.bottom = -100;
        light.shadow.camera.left = -120;
        light.shadow.camera.right = 120;
        this.scene.add(light);

        // ground
        // var mesh = new THREE.Mesh(new THREE.PlaneBufferGeometry(4000, 4000), new THREE.MeshPhongMaterial({ color: 0x29294b, depthWrite: false }));
        // mesh.rotation.x = - Math.PI / 2;
        // //mesh.position.y = -100;
        // mesh.receiveShadow = true;
        // this.scene.add(mesh);

        // var grid = new THREE.GridHelper(4000, 60, 0x000000, 0x000000);
        // //grid.position.y = -100;
        // grid.material.opacity = 0.2;
        // grid.material.transparent = true;
        // this.scene.add(grid);

        // model
        const loader = new THREE.FBXLoader();
        const game = this;

        const people = ['BeachBabe', 'BusinessMan', 'Doctor', 'FireFighter', 'Housewife', 'Policeman', 'Prostitute', 'Punk', 'RiotCop', 'Roadworker', 'Robber', 'Sheriff', 'Streetman', 'Waitress'];

        loader.load(`assets/fbx/people/${sessionStorage.getItem("model")}.fbx`, function (object) {

            object.mixer = new THREE.AnimationMixer(object);
            game.player.mixer = object.mixer;
            game.player.root = object.mixer.getRoot();

          object.name = "FireFighter";

            object.traverse(function (child) {
                if (child.isMesh) {
                    child.castShadow = true;
                    child.receiveShadow = false;
                }
            });

            const tLoader = new THREE.TextureLoader();
            tLoader.load(`assets/images/SimplePeople_${sessionStorage.getItem("model")}_${sessionStorage.getItem("color")}.png`, function (texture) {
                object.traverse(function (child) {
                    if (child.isMesh) {
                        child.material.map = texture;
                    }
                });
            });

            game.scene.add(object);
            game.player.object = object;
            game.animations.Idle = object.animations[0];
            // game.animate();
            game.loadNextAnim(loader);
        });


        this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
        this.renderer.setPixelRatio(window.devicePixelRatio);
        this.renderer.setSize(window.innerWidth, window.innerHeight);
        // this.renderer.setClearAlpha(0.2);
        this.renderer.shadowMap.enabled = true;
        this.container.appendChild(this.renderer.domElement);

        this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
        this.controls.target.set(0, 150, 0);
        this.controls.update();

        

        window.addEventListener('resize', function () { game.onWindowResize(); }, false);
    }

    loadNextAnim(loader){
		let anim = this.anims.pop();
		const game = this;
		loader.load( `${this.assetsPath}fbx/anims/${anim}.fbx`, function( object ){
			game.animations[anim] = object.animations[0];
			if (game.anims.length>0){
				game.loadNextAnim(loader);
			}else{
				delete game.anims;
				game.action = "Idle";
				game.animate();
			}
		});	
	}

    onWindowResize() {
        this.camera.aspect = window.innerWidth / window.innerHeight;
        this.camera.updateProjectionMatrix();

        this.renderer.setSize(window.innerWidth, window.innerHeight);

    }

    set action(name){
		const action = this.player.mixer.clipAction( this.animations[name] );
        action.time = 0;
		this.player.mixer.stopAllAction();
		this.player.action = name;
		this.player.actionTime = Date.now();
        this.player.actionName = name;
		
		action.fadeIn(0.5);	
		action.play();
	}

    get action(){
        if (this.player===undefined || this.player.actionName===undefined) return "";
        return this.player.actionName;
    }

    toggleAnimation(){
        if (game.action=="Idle"){
            game.action = "Pointing Gesture";
        } else if (game.action == "Pointing Gesture"){
            game.action = "Pointing";
        } else if (game.action == "Pointing") {
            game.action = "Running";
        } else if (game.action == "Running") {
            game.action = "Talking";
        } else if (game.action == "Talking") {
            game.action = "Walking";
        }else{
            game.action = "Idle";
        }
    }

    animate() {
        const game = this;
        const dt = this.clock.getDelta();

        requestAnimationFrame(function () { game.animate(); });

        if (this.player.mixer !== undefined) this.player.mixer.update(dt);

        // this.camera.position.set(-200, 200, 500);
        this.renderer.render(this.scene, this.camera);

    }
}